package com.ys.service.business.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ys.entity.amazonorder.*;
import com.ys.entity.base.TbMaterial;
import com.ys.entity.base.TsBatchImportInfo;
import com.ys.entity.base.TsBatchImportLog;
import com.ys.entity.business.*;
import com.ys.entity.storage.TccAssemblyMaintain;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsMenuNo;
import com.ys.enume.base.TsBatchImportLogEnum;
import com.ys.enume.business.TpProductMaterialEnum;
import com.ys.enume.purchase.TcgPurchaseByOrderEnum;
import com.ys.mapper.base.BaseDiyMapper;
import com.ys.mapper.base.TsBatchImportInfoMapper;
import com.ys.mapper.base.TsBatchImportLogMapper;
import com.ys.mapper.business.*;
import com.ys.mapper.storage.TccAssemblyMaintainMapper;
import com.ys.mapper.sys.YsMenuNoMapper;
import com.ys.util.CheckUtil;
import com.ys.util.DateUtil;
import com.ys.util.RandomUtil;
import com.ys.util.shiro.ShiroUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.vo.R;
import com.ys.dto.AddDto;
import com.ys.dto.EditDto;
import com.ys.service.business.TpProductBasicService;

@Service("tpProductBasicService")
public class TpProductBasicServiceImpl implements TpProductBasicService {

	private static final Logger logger = LoggerFactory.getLogger(TpProductBasicServiceImpl.class);


	public static Long MENU_ID = 10183L;
	
	@Autowired
	private TpProductBasisMapper tpProductBasisMapper;
	@Autowired
	private TpProductBasisComponentMapper tpProductBasisComponentMapper;
	@Autowired
	private DiySqlMapper diySqlMapper;

	@Autowired
	private TsBatchImportInfoMapper tsBatchImportInfoMapper;

	@Autowired
	private TsBatchImportLogMapper tsBatchImportLogMapper;


	@Autowired
	private BaseDiyMapper baseDiyMapper;


	@Autowired
	private YsMenuNoMapper ysMenuNoMapper;

	@Autowired
	private TpProductMaterialMapper tpProductMaterialMapper;

    @Autowired
    private TpProductActiveMapper tpProductActiveMapper;

	@Autowired
	private TpProductActiveComponentMapper tpProductActiveComponentMapper;

	@Autowired
	private CheckUtil checkUtil;

	@Autowired
	private TccAssemblyMaintainMapper tccAssemblyMaintainMapper;


	@Override
	public R add(Map<String, Object> params) {
		
		String code = params.get("code").toString();
		if (code == null ) {
			return R.error("商品编码不能为空");
		} else if (new TpProductBasis().setCode(code).count() > 0) {
			return R.error("该商品已存在");
		}
		
		TpProductBasis entity = JSON.parseObject(JSON.toJSONString(params), TpProductBasis.class);
		tpProductBasisMapper.insert(entity);
		return R.ok(AddDto.closeAndReload());
	}
	
	@Override
	public R edit(Map<String, Object> params, String sonlist) {
		
		// 验证编码
		String code = params.get("code").toString();
		if (new TpProductBasis().setCode(code).where("A.Id != '" + params.get("id").toString() + "'").count() > 0) {
			return R.error("商品已存在");
		}

		TpProductBasis entity = JSON.parseObject(JSON.toJSONString(params), TpProductBasis.class);
		tpProductBasisMapper.update(entity);
		
		// 修改子件
		JSONArray sons = JSON.parseArray(sonlist);
		for (int i = 0; i < sons.size(); i++) {
			JSONObject JO = sons.getJSONObject(i);
			TpProductBasisComponent son = JSON.parseObject(JO.toJSONString(), TpProductBasisComponent.class);
			tpProductBasisComponentMapper.update(son);
		}
		return R.ok(EditDto.closeAndReload());
	}

	@Override
	public R export(Map<String, Object> params) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public R search(Map<String, Object> params) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 删除
	 * @operateCompanyId operateCompanyId
	 * @return
	 */
	@Override
	@Transactional
	public R deleteTpProductBasic(Map<String, Object> params) {
		String[] strs = params.get("list").toString().split(",");
		for(int i=0,len=strs.length;i<len;i++){

			diySqlMapper.deleteTpProductBasis(Long.valueOf(strs[i]));
		}

		return R.ok(EditDto.closeAndReload());
	
	}



	//商品库批量导入 - 导入都结束的时候做的操作
	@Override
	public void importInfoFromBatchImportLogByMain(){
		TsBatchImportInfo tsBatchImportInfo = new TsBatchImportInfo()
				.setStatus(0)
				.setImportInfoState(0)
				.setUserId(ShiroUtils.getUserId())
				.setInfoType(TsBatchImportLogEnum.InfoType.TP_ProductBasis.value)
				;
		tsBatchImportInfoMapper.insert(tsBatchImportInfo);
		//将导入的具体信息的父id设置成 该母表信息
		baseDiyMapper.updateTsBatchImportLogInfoByImportProductBase(ShiroUtils.getUserId(), TsBatchImportLogEnum.InfoType.TP_ProductBasis.value, tsBatchImportInfo.getId());

		//
//		List<TsBatchImportLog> logList = new TsBatchImportLog()
//				.setPid(tsBatchImportInfo.getId())
//				.setUserId(ShiroUtils.getUserId())
//				.setInfoType(TsBatchImportLogEnum.InfoType.TP_ProductBasis.value)
//				.setImportState(TsBatchImportLogEnum.ImportState.NO.value)
//				.queryList();
//		//导入都结束后 ， 读取导入的Log数据，然后新增数据
//		if(logList!=null && logList.size()>0){
//			for(TsBatchImportLog tsBatchImportLog:logList){
//				tsBatchImportLog.setImportState(TsBatchImportLogEnum.ImportState.SUCCESS.value);//暂时将
//				tsBatchImportLog.setFailReason("子件未导入");
//				tsBatchImportLogMapper.update(tsBatchImportLog);
//			}
//		}
		int importInfoState = 1;
		int count = new TsBatchImportLog().setPid(tsBatchImportInfo.getId()).setImportState(TsBatchImportLogEnum.ImportState.FAIL.value).count();
		if(count>0){
			importInfoState = 2;
		}
		TsBatchImportInfo infoByUpdate = new TsBatchImportInfo().setId(tsBatchImportInfo.getId()).setImportInfoState(importInfoState);
		tsBatchImportInfoMapper.update(infoByUpdate);
	}




	//商品库子件批量导入 - 导入都结束的时候做的操作
	@Override
	public void importInfoFromBatchImportLogBySub()throws Exception {

		TsUserChange tsUserChange = new TsUserChange().setUserId(ShiroUtils.getUserId()).setStatus(1).queryFirst();
		TsBatchImportInfo tsBatchImportInfo = new TsBatchImportInfo()
				.setStatus(0)
				.setUserId(ShiroUtils.getUserId())
				.setInfoType(TsBatchImportLogEnum.InfoType.TP_ProductBasis.value)
				.setOrderby("A.Id DESC")
				.queryFirst();
		if(tsBatchImportInfo!=null && tsBatchImportInfo.getId()!=null){
			//tsBatchImportInfoMapper.insert(tsBatchImportInfo);
			baseDiyMapper.updateTsBatchImportLogInfoByImportProductBase(ShiroUtils.getUserId(), TsBatchImportLogEnum.InfoType.TP_ProductBasisComponent.value, tsBatchImportInfo.getId());

			//获取导入的商品库详情数据
			List<TsBatchImportLog> productList = new TsBatchImportLog()
					.setPid(tsBatchImportInfo.getId())
					.setUserId(ShiroUtils.getUserId())
					.setInfoType(TsBatchImportLogEnum.InfoType.TP_ProductBasis.value)
					//.setImportState(TsBatchImportLogEnum.ImportState.NO.value)
					.queryList();

			//获取导入的商品库子件表详情数据
			List<TsBatchImportLog> subList = new TsBatchImportLog()
					.setPid(tsBatchImportInfo.getId())
					.setUserId(ShiroUtils.getUserId())
					.setInfoType(TsBatchImportLogEnum.InfoType.TP_ProductBasisComponent.value)
					.setImportState(TsBatchImportLogEnum.ImportState.NO.value)
					.queryList();

			//导入都结束后 ， 读取导入的Log数据，然后新增数据
			if(productList!=null && productList.size()>0 && subList!=null && subList.size()>0){
				//遍历
				for(TsBatchImportLog productItem:productList){
					String productInfoByStr = productItem.getImportInfo();
					JSONObject productInfo = JSONObject.parseObject(productInfoByStr);
					String pNo = productInfo.get("pNo").toString().trim();//母件序号

					//根据母件序号，获取对应子件信息
					List<TsBatchImportLog> subListByNo = subList.stream().filter(tsBatchImportLog->{
						boolean res = false;
						String importInfo = tsBatchImportLog.getImportInfo();
						JSONObject info = JSONObject.parseObject(importInfo);
						String subNo = info.get("subNo").toString().trim();//子件序号
						//如果子件序号包含 -
						if(subNo.contains("-")){
							subNo = subNo.split("-")[0];
						}
						if(Integer.parseInt(pNo)==Integer.parseInt(subNo)){
							res = true;
						}
						return res;
					}).collect(Collectors.toList());

					if(subListByNo.size()>0){

						//新增母件信息
						String preCode = "NP";
						String code = getBm(MENU_ID, preCode);
						if (new TpProductBqSp().setCode(code).count() > 0) {
							productItem.setImportState(TsBatchImportLogEnum.ImportState.FAIL.value);
							productItem.setFailReason("商品编码【"+code+"】重复生成，请核实!");
							tsBatchImportLogMapper.update(productItem);
						}
						TpProductBasis tpProductBasis = new TpProductBasis();
                        TpProductActive tpProductActive = new TpProductActive();

                        //商品编码
						tpProductBasis.setCode(code);
                        tpProductActive.setCode(code);
                        //合并商品编码
                        tpProductBasis.setCodeMerge(code);
                        tpProductActive.setCodeMerge(code);

						//商品名称
						if(productInfo.get("productName")!=null && !"".equals(productInfo.get("productName").toString().trim())) {
							tpProductBasis.setName(productInfo.get("productName").toString().trim());
							tpProductActive.setName(productInfo.get("productName").toString().trim());
						}

                        //商品品类
						if(productInfo.get("commodityPl")!=null && !"".equals(productInfo.get("commodityPl").toString().trim())) {
							TbBaseinfoSppl tbBaseinfoSppl = new TbBaseinfoSppl().setCategoryCn(productInfo.get("commodityPl").toString().trim()).queryFirst();
							if(tbBaseinfoSppl!=null && tbBaseinfoSppl.getId()!=null){
								tpProductBasis.setCommodityPlId(tbBaseinfoSppl.getId());
								tpProductActive.setCommodityPlId(tbBaseinfoSppl.getId());
							}
						}

						//商品组合
						if(productInfo.get("productCombination")!=null) {
							tpProductBasis.setCombination(productInfo.get("productCombination").toString().trim());
							tpProductActive.setCombination(productInfo.get("productCombination").toString().trim());
						}

                        //海关编码
						if(productInfo.get("hgCode")!=null) {
						    tpProductBasis.setCodeHs(productInfo.get("hgCode").toString().trim());
                            tpProductActive.setCodeHs(productInfo.get("hgCode").toString().trim());
                        }

						//商品单位
						if(productInfo.get("nameUnit")!=null && !"".equals(productInfo.get("nameUnit").toString().trim())) {
							TbBaseinfoDwmc tbBaseinfoDwmc = new TbBaseinfoDwmc().setNameUnitCn(productInfo.get("nameUnit").toString().trim()).queryFirst();
							if(tbBaseinfoDwmc!=null && tbBaseinfoDwmc.getId()!=null){
								tpProductBasis.setNameUnitId(tbBaseinfoDwmc.getId());
                                tpProductActive.setNameUnitId(tbBaseinfoDwmc.getId());
							}
						}
						//商品品名(中)
						if(productInfo.get("name")!=null && !"".equals(productInfo.get("name").toString().trim())) {
							TbBaseinfoSppm tbBaseinfoSppm = new TbBaseinfoSppm().setNameCn(productInfo.get("name").toString().trim()).queryFirst();
							if(tbBaseinfoSppm!=null && tbBaseinfoSppm.getId()!=null){
								tpProductBasis.setNameId(tbBaseinfoSppm.getId());
                                tpProductActive.setNameId(tbBaseinfoSppm.getId());
							}
						}
						//商品用途(中)
						if(productInfo.get("usage")!=null && !"".equals(productInfo.get("usage").toString().trim())) {
							TbBaseinfoSpyt tbBaseinfoSpyt = new TbBaseinfoSpyt().setUsageCn(productInfo.get("usage").toString().trim()).queryFirst();
							if(tbBaseinfoSpyt!=null && tbBaseinfoSpyt.getId()!=null){
								tpProductBasis.setUsageId(tbBaseinfoSpyt.getId());
                                tpProductActive.setUsageId(tbBaseinfoSpyt.getId());
							}
						}

						//商品材质(中)
						if(productInfo.get("material")!=null && !"".equals(productInfo.get("material").toString().trim())) {
							StringBuilder material = new StringBuilder();//商品材质
							if(productInfo.get("material").toString().contains(",")){
								String[] materialArr = material.toString().split(",");
								for(String info:materialArr){
									if(material.length()>0){
										material.append(",");
									}
									material.append("'").append(info).append("'");
								}
							}else {
								material = new StringBuilder().append("'").append(productInfo.get("material").toString().trim()).append("'");//商品材质
							}
							List<TbBaseinfoSpcz> tbBaseinfoSpczList = new TbBaseinfoSpcz().where("A.MaterialCn IN ("+material.toString()+")").queryList();
							if(tbBaseinfoSpczList!=null && tbBaseinfoSpczList.size()>0){
								for(TbBaseinfoSpcz tbBaseinfoSpcz:tbBaseinfoSpczList){
									TpProductMaterial tpProductMaterial = new TpProductMaterial()
											.setType(TpProductMaterialEnum.Type.TP_ProductBasis.value)
											.setProductCode(code)
											.setMaterialNameCn(tbBaseinfoSpcz.getMaterialCn())
											.setMaterialNameEn(tbBaseinfoSpcz.getMaterialEn())
											.setMaterialId(tbBaseinfoSpcz.getId())
											.setStatus(1);
                                    TpProductMaterial tpProductMaterialByActive = new TpProductMaterial()
                                            .setType(TpProductMaterialEnum.Type.TP_ProductActive.value)
                                            .setProductCode(code)
                                            .setMaterialNameCn(tbBaseinfoSpcz.getMaterialCn())
                                            .setMaterialNameEn(tbBaseinfoSpcz.getMaterialEn())
                                            .setMaterialId(tbBaseinfoSpcz.getId())
                                            .setStatus(1);
                                    tpProductMaterialMapper.insert(tpProductMaterial);
                                    tpProductMaterialMapper.insert(tpProductMaterialByActive);
								}

							}
						}

						//商品长度(cm)
						if(productInfo.get("productLong")!=null && !"".equals(productInfo.get("productLong").toString().trim()) && checkUtil.isNumber(productInfo.get("productLong").toString().trim())){
                            tpProductBasis.setSizeLength(new BigDecimal(productInfo.get("productLong").toString().trim()));//商品长度(cm)
						    tpProductActive.setSizeLength(new BigDecimal(productInfo.get("productLong").toString().trim()));//商品长度(cm)
                        }

						//商品宽度(cm)
						if(productInfo.get("productWidth")!=null && !"".equals(productInfo.get("productWidth").toString().trim()) && checkUtil.isNumber(productInfo.get("productWidth").toString().trim())){
                            tpProductBasis.setSizeWidth(new BigDecimal(productInfo.get("productWidth").toString().trim()));//商品宽度(cm)
						    tpProductActive.setSizeWidth(new BigDecimal(productInfo.get("productWidth").toString().trim()));//商品宽度(cm)
                        }

						//商品高度(cm)
						if(productInfo.get("productHeight")!=null && !"".equals(productInfo.get("productHeight").toString().trim()) && checkUtil.isNumber(productInfo.get("productHeight").toString().trim())){
                            tpProductBasis.setSizeHeight(new BigDecimal(productInfo.get("productHeight").toString().trim()));//商品高度(cm)
                            tpProductActive.setSizeHeight(new BigDecimal(productInfo.get("productHeight").toString().trim()));//商品高度(cm)
                        }


						//商品重量（g）
						if(productInfo.get("productWeight")!=null && !"".equals(productInfo.get("productWeight").toString().trim()) && checkUtil.isNumber(productInfo.get("productWeight").toString().trim())){
                            tpProductBasis.setSizeWeight(new BigDecimal(productInfo.get("productWeight").toString().trim()));//商品重量（g）
                            tpProductActive.setSizeWeight(new BigDecimal(productInfo.get("productWeight").toString().trim()));//商品重量（g）
                        }

						//采购链接
						if(productInfo.get("linkIn")!=null && !"".equals(productInfo.get("linkIn").toString().trim())){
                            tpProductBasis.setLinkIn(productInfo.get("linkIn").toString().trim());//采购链接
                            tpProductActive.setLinkIn(productInfo.get("linkIn").toString().trim());//采购链接
                        }

						//公司编码
						if(productInfo.get("vgsbm")!=null && !"".equals(productInfo.get("vgsbm").toString().trim())){
							tpProductBasis.setVgsBm(productInfo.get("vgsbm").toString().trim());//公司编码
							tpProductActive.setVgsBm(productInfo.get("vgsbm").toString().trim());//公司编码
						}

                        String commodityProperty = "新品";

                        tpProductBasis.setCommodityProperty(commodityProperty);//商品属性
                        tpProductBasis.setVsfJp("否");
                        tpProductBasis.setIsSuperior("否");
                        tpProductBasis.setIsUsable("启用");
                        tpProductBasis.setStatus(1);

                        tpProductActive.setCommodityProperty(commodityProperty);//商品属性
                        tpProductActive.setVsfJp("否");
                        tpProductActive.setIsSuperior("否");
                        tpProductActive.setIsUsable("1");
                        tpProductActive.setDeclarationElements("0");//报关要素，默认为否
                        tpProductActive.setStatus(1);

						//新增商品库信息
						tpProductBasisMapper.insert(tpProductBasis);
						//新增Listing库信息
                        tpProductActiveMapper.insert(tpProductActive);

                        int subCodeNo = 0;
						//遍历子件信息、并新增
						for(TsBatchImportLog subItem:subListByNo){
							subCodeNo++;
                            String subImportInfo = subItem.getImportInfo();
                            JSONObject subInfo = JSONObject.parseObject(subImportInfo);
                            logger.info("subInfo："+subInfo);

							//TODO 产品图片 subImg

                            TpProductBasisComponent tpProductBasisComponent = new TpProductBasisComponent();
                            TpProductActiveComponent tpProductActiveComponent = new TpProductActiveComponent();

                            //母件编码
                            tpProductBasisComponent.setPcode(tpProductBasis.getCode());
                            tpProductActiveComponent.setPcode(tpProductBasis.getCode());

                            //子件名称
                            if(subInfo.get("subName")!=null) {
                                tpProductBasisComponent.setName(subInfo.get("subName").toString().trim());
                                tpProductActiveComponent.setName(subInfo.get("subName").toString().trim());
                            }

							//子件编码
							String currentNoNew = String.format("%02d",subCodeNo);
							//商品编码-01，-02，-03.....
							String subCode = tpProductBasis.getCode()+"-"+currentNoNew;

							tpProductBasisComponent.setCode(subCode);
							tpProductActiveComponent.setCode(subCode);
							//子件合并编码
							tpProductBasisComponent.setSubCodeMerge(subCode);
							tpProductActiveComponent.setSubCodeMerge(subCode);


							//子件数量
                            if(subInfo.get("subNum")!=null && !"".equals(subInfo.get("subNum").toString().trim()) && checkUtil.isNumber(subInfo.get("subNum").toString().trim())) {
                                tpProductBasisComponent.setNum(new BigDecimal(subInfo.get("subNum").toString().trim()));
                                tpProductActiveComponent.setNum(new BigDecimal(subInfo.get("subNum").toString().trim()));
                            }

                            //子件单价
                            if(subInfo.get("subAmount")!=null && !"".equals(subInfo.get("subAmount").toString().trim()) && checkUtil.isNumber(subInfo.get("subAmount").toString().trim())) {
                                tpProductBasisComponent.setBprice(new BigDecimal(subInfo.get("subAmount").toString().trim()));
                                tpProductActiveComponent.setBprice(new BigDecimal(subInfo.get("subAmount").toString().trim()));
                            }

							//采购链接
                            if(subInfo.get("subLinkIn")!=null) {
                                tpProductBasisComponent.setLinkIn(subInfo.get("subLinkIn").toString().trim());
                                tpProductActiveComponent.setLinkIn(subInfo.get("subLinkIn").toString().trim());
                            }

							//铺货标识
                            if(subInfo.get("linkInMark")!=null) {
                                tpProductBasisComponent.setLinkInMark(subInfo.get("linkInMark").toString().trim());
                                tpProductActiveComponent.setLinkInMark(subInfo.get("linkInMark").toString().trim());
                            }

							//子件备注
                            if(subInfo.get("subRemark")!=null) {
                                tpProductBasisComponent.setRemark(subInfo.get("subRemark").toString().trim());
                                tpProductActiveComponent.setRemark(subInfo.get("subRemark").toString().trim());
                            }

                            //海关编码
                            if(tpProductBasis.getCodeHs()!=null){
                                tpProductBasisComponent.setCustomsCode(tpProductBasis.getCodeHs());
                                tpProductActiveComponent.setCustomsCode(tpProductBasis.getCodeHs());
                            }


							tpProductBasisComponentMapper.insert(tpProductBasisComponent);
							tpProductActiveComponentMapper.insert(tpProductActiveComponent);

							//修改导入状态
							subItem.setImportState(TsBatchImportLogEnum.ImportState.SUCCESS.value);
							subItem.setLevIdOne(productItem.getId());//设置id
							tsBatchImportLogMapper.update(subItem);
						}


						//新增组装方案维护
						TccAssemblyMaintain tccAssemblyMaintain = new TccAssemblyMaintain();
						tccAssemblyMaintain.setGuid(RandomUtil.getGUID());
						tccAssemblyMaintain.setName("ZZFA001");
						tccAssemblyMaintain.setWay("人工");
						tccAssemblyMaintain.setProductName(tpProductActive.getName());
						tccAssemblyMaintain.setProductID(tpProductBasis.getCode());
						tccAssemblyMaintain.setLength(new BigDecimal("0.1"));
						tccAssemblyMaintain.setWidth(new BigDecimal("0.1"));
						tccAssemblyMaintain.setWidth(new BigDecimal("0.1"));
						tccAssemblyMaintain.setWeight(new BigDecimal("0.1"));
						if(tsUserChange!=null){
							tccAssemblyMaintain.setCreateUser(tsUserChange.getUserId());
							tccAssemblyMaintain.setUpdateUser(tsUserChange.getUserId());
						}

						tccAssemblyMaintain.setProductLength(BigDecimal.ZERO);
						tccAssemblyMaintain.setProductWeight(BigDecimal.ZERO);
						tccAssemblyMaintain.setProductWidth(BigDecimal.ZERO);
						tccAssemblyMaintain.setProductHeight(BigDecimal.ZERO);
						tccAssemblyMaintain.setStatus(1);
						tccAssemblyMaintainMapper.insert(tccAssemblyMaintain);

						//修改导入状态
                        productItem.setImportState(TsBatchImportLogEnum.ImportState.SUCCESS.value);
                        tsBatchImportLogMapper.update(productItem);
					}else {
						productItem.setImportState(TsBatchImportLogEnum.ImportState.FAIL.value);
						productItem.setFailReason("该母件无子件信息");
						tsBatchImportLogMapper.update(productItem);
					}
				}


				//查询是否还有未匹配到商品母件的子件
				//再次 获取：导入的商品库子件表详情数据
				List<TsBatchImportLog> subListAgain = new TsBatchImportLog()
						.setPid(tsBatchImportInfo.getId())
						.setUserId(ShiroUtils.getUserId())
						.setInfoType(TsBatchImportLogEnum.InfoType.TP_ProductBasisComponent.value)
						.setImportState(TsBatchImportLogEnum.ImportState.NO.value)
						.queryList();

				if(subListAgain!=null && subListAgain.size()>0){
					for(TsBatchImportLog subItem:subListAgain){
						subItem.setImportState(TsBatchImportLogEnum.ImportState.FAIL.value);
						subItem.setFailReason("该子件未匹配到对应母件信息");
						tsBatchImportLogMapper.update(subItem);
					}

				}
			}

			///最后修改导入状态
			int importInfoState = 1;
			int count = new TsBatchImportLog().setPid(tsBatchImportInfo.getId()).setImportState(TsBatchImportLogEnum.ImportState.FAIL.value).count();
			if(count>0){
				importInfoState = 2;
			}
			TsBatchImportInfo infoByUpdate = new TsBatchImportInfo()
					.setId(tsBatchImportInfo.getId())
					.setImportInfoState(importInfoState)
					.setStatus(1)//代表子表数据已导入
					;
			tsBatchImportInfoMapper.update(infoByUpdate);
		}

	}



	/**
	 * 批量导入
	 */
	@Override
	public R importInfo(String rows, Long menuId){
		try {
			List<TsBatchImportLog> list = new ArrayList<>();
			String userId = ShiroUtils.getUserId();
			//获取导入数据
			JSONArray detailList = JSON.parseArray(rows);
			for(int i=0;i<detailList.size();i++){
				JSONObject info = detailList.getJSONObject(i);
				if(info!=null){
					TsBatchImportLog tsBatchImportLog = new TsBatchImportLog();
					tsBatchImportLog.setUserId(userId);
					tsBatchImportLog.setImportInfo(info.toJSONString());
					tsBatchImportLog.setInfoType(TsBatchImportLogEnum.InfoType.TP_ProductBasis.value);
					tsBatchImportLog.setImportState(TsBatchImportLogEnum.ImportState.NO.value);
					tsBatchImportLog.setStatus(0);
					list.add(tsBatchImportLog);
				}
			}
			if(list.size()>0){
				baseDiyMapper.insertBatchTsBatchImportLog(list);
			}
		}catch (Exception e){
			logger.error("导入出错：",e.getMessage(),e);
			return R.error("导入出错,请稍后重试!");
		}
		return R.ok("请点击“导入详情”按钮查看导入进度！");
	}




	/**
	 * 批量导入子件数据到 日志表中
	 */
	@Override
	public R importInfoBySub(String rows, Long menuId){
		try {
			//验证母表是否已经导入成功
			int isAdded = new TsBatchImportInfo()
					.setStatus(0)
					.setImportInfoState(1)
					.setUserId(ShiroUtils.getUserId())
					.setInfoType(TsBatchImportLogEnum.InfoType.TP_ProductBasis.value)
					.count();
			if(isAdded<=0){
				return R.error("请先导入母表信息!");
			}


			List<TsBatchImportLog> list = new ArrayList<>();
			String userId = ShiroUtils.getUserId();
			//获取导入数据
			JSONArray detailList = JSON.parseArray(rows);
			for(int i=0;i<detailList.size();i++){
				JSONObject info = detailList.getJSONObject(i);
				if(info!=null){
					TsBatchImportLog tsBatchImportLog = new TsBatchImportLog();
					tsBatchImportLog.setUserId(userId);
					tsBatchImportLog.setImportInfo(info.toJSONString());
					tsBatchImportLog.setInfoType(TsBatchImportLogEnum.InfoType.TP_ProductBasisComponent.value);
					tsBatchImportLog.setImportState(TsBatchImportLogEnum.ImportState.NO.value);
					tsBatchImportLog.setStatus(0);
					list.add(tsBatchImportLog);
				}
			}
			if(list.size()>0){
				baseDiyMapper.insertBatchTsBatchImportLog(list);
			}
		}catch (Exception e){
			logger.error("导入出错：",e.getMessage(),e);
			return R.error("导入出错,请稍后重试!");
		}
		return R.ok("请点击“导入详情”按钮查看导入进度！");
	}



	/**
	 * 获取商品编码
	 */
	private String getBm(Long menuId,String preCode) throws Exception {

		YsMenuNo entity = new YsMenuNo().setMenuId(menuId).queryFirst();
		if (entity == null) {
			throw new Exception("尚未设置单号格式");
		} else {

			String today = DateUtil.getYYYY_MM_DD(new Date());

			String connectCode = entity.getConnectCode();
			String middleCode = today.replace("-", "").substring(2);
			Integer currentNo = entity.getCurrentNo();
			if (entity.getCurrentDay().equals(today)) {

				// 当前日期是当天的，则序号+1
				entity.setCurrentNo(currentNo + 1);
				ysMenuNoMapper.update(entity);
				String currentNoNew = String.format("%04d",currentNo);
				return preCode + connectCode + middleCode + connectCode + currentNoNew;
			} else {

				// 当前日期不是当天的，则序号回归，日期回归当天
				currentNo = entity.getStartNo();
				entity.setCurrentNo(currentNo + 1)
						.setCurrentDay(today);
				ysMenuNoMapper.update(entity);
				String currentNoNew = String.format("%04d",currentNo);
				return preCode + connectCode + middleCode + connectCode + currentNoNew;
			}
		}
	}





}
